package com.wd.live.ui.fragment

import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView.Adapter
import com.billy.android.swipe.SwipeConsumerExclusiveGroup
import com.billy.android.swipe.consumer.SlidingConsumer
import com.bumptech.glide.Glide
import com.opensource.svgaplayer.SVGACallback
import com.wd.live.R
import com.wd.live.databinding.FragmentNearBinding
import com.wd.live.databinding.ItemNearListBinding
import com.wd.live.tool.BindingViewHolder
import com.wd.live.tool.LocalData
import com.wd.live.tool.longToast
import com.wd.live.tool.newBindingViewHolder
import com.wd.live.viewmodel.MainViewModel

// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

/**
 * A simple [Fragment] subclass.
 * Use the [NearFragment.newInstance] factory method to
 * create an instance of this fragment.
 */
class NearFragment : Fragment(R.layout.fragment_near) {
    private var _binding: FragmentNearBinding? = null
    private var param1: String? = null
    private var param2: String? = null
    private val binding get() = _binding!!
    private val viewModel: MainViewModel by viewModels(ownerProducer = { requireActivity() })
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            param1 = it.getString(ARG_PARAM1)
            param2 = it.getString(ARG_PARAM2)
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentNearBinding.inflate(inflater, container, false)
        return binding.root
    }
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        //开始动画,监听动画过程
        binding.locationSvga.callback = object : SVGACallback {
            override fun onFinished() {
                Log.d("SVGACallback", "onFinished")
            }

            override fun onPause() {
                Log.d("SVGACallback", "onPause")
            }

            override fun onRepeat() {
                Log.d("SVGACallback", "onRepeat")
            }

            override fun onStep(frame: Int, percentage: Double) {
            }

        }
        viewModel.location.observe(viewLifecycleOwner) {
            Log.i("AMapLocationListener", "${it.latitude} / ${it.longitude}")
            viewModel.getNearList(it.longitude.toString(), it.latitude.toString(), 1)
            binding.locationText.text = it.address
        }

        viewModel.nearList.observe(viewLifecycleOwner) { _list ->
            binding.list.apply {
                layoutManager = LinearLayoutManager(context)
                adapter = MyAdapter(_list) { liveId ->
                    //接受item单击事件
                    longToast("跳转到直播间$liveId")
                }
            }
        }
    }

    companion object {
        /**
         * Use this factory method to create a new instance of
         * this fragment using the provided parameters.
         *
         * @param param1 Parameter 1.
         * @param param2 Parameter 2.
         * @return A new instance of fragment NearFragment.
         */
        // TODO: Rename and change types and number of parameters
        @JvmStatic
        fun newInstance() =
            NearFragment()
    }

    class MyAdapter(
        private val list: ArrayList<LocalData.BroadcasterInfo>,
        private val fucntion: (String) -> Unit
    ) : Adapter<BindingViewHolder<ItemNearListBinding>>() {

        //侧滑效果需要的对象
        private val swipeConsumerExclusiveGroup: SwipeConsumerExclusiveGroup =
            SwipeConsumerExclusiveGroup(true)

        override fun onCreateViewHolder(
            parent: ViewGroup,
            viewType: Int
        ): BindingViewHolder<ItemNearListBinding> {
            //通过这个方法创建一个viewHolder。这个viewHolder是基于viewBinding的
            return newBindingViewHolder(parent)

        }

        override fun getItemCount(): Int = list.size
        override fun onBindViewHolder(
            holder: BindingViewHolder<ItemNearListBinding>,
            position: Int
        ) {
            val info = list[position]
            val slidingConsumer = SlidingConsumer()
            holder.binding.mainUiWrapView.addConsumer(slidingConsumer)
                ?.setRelativeMoveFactor(SlidingConsumer.FACTOR_FOLLOW)?.maxSettleDuration = 600
            slidingConsumer.addToExclusiveGroup(swipeConsumerExclusiveGroup)
            holder.binding.ivOpen.setOnClickListener {
                fucntion.invoke("liveId")
                //关闭菜单
                slidingConsumer.close()
            }
            Glide.with(holder.binding.liveHeader).load(info.headPic).into(holder.binding.liveHeader)
            holder.binding.liveHeader
            holder.binding.liveName.text = info.nickName
            holder.binding.liveSex.setImageResource(if (info.sex == 1) R.mipmap.ic_man else R.mipmap.ic_woman)
        }
    }

    override fun onDetach() {
        super.onDetach()
        binding.locationSvga.stopAnimation(true)
        //释放资源
        _binding = null
    }
}